import * as THREE from 'three'
import { FontLoader } from "three/examples/jsm/loaders/FontLoader";
import { TextGeometry } from "three/examples/jsm/geometries/TextGeometry";

class Tile {
  constructor(opt = {}) {
    this.scene = opt.ctx;
    this.x = opt.x;
    this.y = opt.y;
    this.row = opt.row;
    this.col = opt.col;
    this.zoom = opt.zoom;
    this.loaded = false;
    this.cacheKey = `${this.row}-${this.col}-${this.zoom}`;
    this.url = "";
    this.mesh = "";
    this.drawTileBorder = opt.drawTileBorder
    this.drawTileNum = opt.drawTileNum
    this.createUrl();
    this.load();
  }

  createUrl() {
    const domainIndexList = [1, 2, 3, 4];
    const domainIndex =
      domainIndexList[Math.floor(Math.random() * domainIndexList.length)];
    this.url = `https://webrd0${domainIndex}.is.autonavi.com/appmaptile?x=${this.row}&y=${this.col}&z=${this.zoom}&lang=zh_cn&size=1&scale=1&style=8`;
  }

  load() {
    const loader = new THREE.TextureLoader();
    const material = new THREE.MeshBasicMaterial({
      map: loader.load(this.url),
      side: THREE.DoubleSide,
    });
    const planGeo = new THREE.PlaneGeometry(256, 256);
    this.mesh = new THREE.Mesh(planGeo, material);

    this.render();
  }
  createRect(x, y) {
    const material = new THREE.LineBasicMaterial({
      color: 0x0000ff,
    });

    const points = [];
    points.push(new THREE.Vector3(x - 128, y + 128, 0));
    points.push(new THREE.Vector3(x + 128, y + 128, 0));
    points.push(new THREE.Vector3(x + 128, y - 128, 0));
    points.push(new THREE.Vector3(x - 128, y - 128, 0));

    const geometry = new THREE.BufferGeometry().setFromPoints(points);

    return new THREE.Line(geometry, material);
  }
  createText(text) {
    const fontLoader = new FontLoader();

    fontLoader.load("./FangSong_GB2312_Regular.json", (res) => {
      const geo = new TextGeometry(text, {
        font: res, // 字体格式
        size: 13, // 字体大小
        height: 1, // 字体深度
        curveSegments: 11, // 曲线控制点数
        bevelEnabled: true, // 斜角
        bevelThickness: 0.1, // 斜角的深度
        bevelSize: 1, // 斜角的大小
        bevelSegments: 1, // 斜角段数
      });
      const material = new THREE.MeshBasicMaterial({ color: "red" });
      const mesh = new THREE.Mesh(geo, material);
      mesh.position.set(this.x, this.y, 0);
      this.scene.add(mesh);
    });
  }
  render() {
    if (this.mesh) {
      this.mesh.position.set(this.x, this.y, 0);
      this.scene.add(this.mesh);
      if (this.drawTileBorder) {
        this.scene.add(this.createRect(this.x, this.y));
      }
      if (this.drawTileNum) {
        this.createText(`${this.row}，${this.col}`)
      }
    }
  }
  updatePos(x, y) {
    this.x = x;
    this.y = y;
    return this;
  }
}

export default Tile